package jmind.dolphin.frame;


import jmind.base.util.DataUtil;
import jmind.base.util.ErrStrFormat;
import jmind.dolphin.redis.*;
import jmind.dolphin.util.DophinUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 事件分发
 * Created by xieweibo on 2016/11/28.
 */
public class Dispatcher {
    private static volatile Dispatcher instance =null;

    public static final Dispatcher getInstance() {
        if(instance==null){
            synchronized (Dispatcher.class){
                if(instance==null){
                    instance=new Dispatcher();
                }
            }
        }

        return instance;
    }

    private  final ServiceFactory serviceFactory = DophinUtil.getServiceFactory();
    private final Logger logger= LoggerFactory.getLogger(getClass());




    public Reply dispatch(final DolphinCommand cmd) throws DolphinException {
        //1.valid cmd
        CommandType commandType = cmd.getCommand();
        if (commandType == null) {
            return new ErrorReply("Command not support");
        }

        switch (commandType) {
            //2.ping command
            case PING: {
                return StatusReply.PONG;
            }
            //3.quit command
            case QUIT: {
                return  StatusReply.QUIT;
            }
            //4.exists command
            case EXISTS: {
                Service service = serviceFactory.getService(cmd.getServiceName());
                if (service == null) {
                    return new IntegerReply(1);
                } else {
                    return new IntegerReply(0);

                }
            }
            default:{
                break;
            }

        }

        if (DataUtil.isEmpty(cmd.getServiceName())) {
            return new ErrorReply(cmd.getCommand() +"has No service name");
        }



        try{

            Service service = serviceFactory.getService(cmd.getServiceName());
            if(service==null){
                return new ErrorReply("ERROR the service  '\" + cmd.getServiceName() + \"' doesn't exists");
            }
           String result ;

            switch (commandType) {
                case GET: {
                    result=service.get(cmd);
                    break;
                }
                case SET: {
                  result=service.set(cmd);
                  break;
                }
                case DEL: {
                   result= service.del(cmd)+"";
                    break;
                }
                default:{
                    result="ERROR unknown command '" + cmd.getCommand() + "'";

                }
            }

           return new BulkReply(result.getBytes());

        }catch (Exception e){
            logger.error(cmd.getServiceName(),e);
            return new ErrorReply(ErrStrFormat.getErrStr(e));
        }
    }


}